<template>
  <div class="maintenance-record">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2 class="page-title">保养记录</h2>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 操作栏 -->
      <div class="action-bar">
        <div class="action-left">
          <el-button type="primary" @click="handleAdd" icon="el-icon-plus">
            +添加计划外保养
          </el-button>
        </div>
        <div class="action-right">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入设备名称/设备编码"
            class="search-input"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #suffix>
              <el-button 
                type="primary" 
                icon="el-icon-search" 
                @click="handleSearch"
                class="search-btn"
              />
            </template>
          </el-input>
          <el-button 
            type="default" 
            icon="el-icon-s-operation" 
            @click="showFilterDialog = true"
            class="filter-btn"
          >
          </el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <div class="table-container">
        <el-table
          :data="tableData"
          v-loading="loading"
          stripe
          border
          style="width: 100%"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="equipmentName" label="设备名称" width="100" align="center" />
          <el-table-column prop="equipmentCode" label="设备编号" width="100" align="center" />
          <el-table-column prop="maintenanceDate" label="保养时间" width="120" align="center" />
          <el-table-column prop="maintenancePerson" label="保养人" width="100" align="center" />
          <el-table-column prop="maintenanceCost" label="保养费用" width="100" align="center">
            <template #default="scope">
              {{ scope.row.maintenanceCost ? '¥' + scope.row.maintenanceCost : '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="maintenanceHours" label="保养工时" width="100" align="center">
            <template #default="scope">
              {{ scope.row.maintenanceHours ? scope.row.maintenanceHours + '小时' : '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="maintenanceItem" label="保养项目" width="110" align="center">
            <template #default="scope">
              {{ scope.row.maintenanceItem || '--' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240" align="center" fixed="right">
            <template #default="scope">
              <button 
                @click="handleView(scope.row)"
                style="color: #409EFF; background: none; border: none; cursor: pointer; margin-right: 8px; text-decoration: underline;"
              >
                查看
              </button>
              <button 
                @click="handleEdit(scope.row)"
                style="color: #E6A23C; background: none; border: none; cursor: pointer; margin-right: 8px; text-decoration: underline;"
              >
                修改
              </button>
              <button 
                @click="handleDelete(scope.row)"
                style="color: #F56C6C; background: none; border: none; cursor: pointer; text-decoration: underline;"
              >
                删除
              </button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="prev, pager, next, jumper, sizes, total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </div>

    <!-- 筛选对话框 -->
    <el-dialog
      v-model="showFilterDialog"
      title="筛选条件"
      width="500px"
      :before-close="handleFilterClose"
    >
      <el-form :model="filterForm" label-width="100px">
        <el-form-item label="保养时间">
          <el-date-picker
            v-model="filterForm.maintenanceDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="保养人">
          <el-input v-model="filterForm.maintenancePerson" placeholder="请输入保养人" clearable />
        </el-form-item>
        <el-form-item label="费用范围">
          <el-input-number v-model="filterForm.minCost" placeholder="最小费用" :min="0" style="width: 45%" />
          <span style="margin: 0 10px">-</span>
          <el-input-number v-model="filterForm.maxCost" placeholder="最大费用" :min="0" style="width: 45%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleFilterClose">取消</el-button>
          <el-button type="primary" @click="handleFilterConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 保养记录详情弹框 -->
    <MaintenanceRecordDetail
      :visible.sync="showDetailDialog"
      :record-data="currentRecord"
    />
  </div>
</template>

<script>
import { maintenanceRecordApi } from '@/api/equipment'
import MaintenanceRecordDetail from './MaintenanceRecordDetail.vue'

export default {
  name: 'MaintenanceRecord',
  components: {
    MaintenanceRecordDetail
  },
  data() {
    return {
      // 表格数据
      tableData: [],
      loading: false,
      
      // 分页参数
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
      // 搜索参数
      searchKeyword: '',
      
      // 筛选参数
      showFilterDialog: false,
      filterForm: {
        maintenanceDateRange: null,
        maintenancePerson: '',
        minCost: null,
        maxCost: null
      },
      
      // 详情弹框参数
      showDetailDialog: false,
      currentRecord: {}
    }
  },
  
  mounted() {
    this.loadData()
  },
  
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          keyword: this.searchKeyword || null,
          ...this.getFilterParams()
        }
        
        const response = await maintenanceRecordApi.getMaintenanceRecordPage(params)
        if (response.code === 200) {
          this.tableData = this.formatTableData(response.data.records || [])
          this.total = response.data.total || 0
        } else {
          this.$message.error(response.message || '加载数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },
    
    // 格式化表格数据
    formatTableData(data) {
      return data.map(item => ({
        ...item,
        maintenanceDate: item.maintenanceDate ? this.formatDate(item.maintenanceDate) : '--'
      }))
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return '--'
      const d = new Date(date)
      return d.getFullYear() + '-' + 
             String(d.getMonth() + 1).padStart(2, '0') + '-' + 
             String(d.getDate()).padStart(2, '0')
    },
    
    // 获取筛选参数
    getFilterParams() {
      const params = {}
      if (this.filterForm.maintenanceDateRange && this.filterForm.maintenanceDateRange.length === 2) {
        params.startDate = this.filterForm.maintenanceDateRange[0]
        params.endDate = this.filterForm.maintenanceDateRange[1]
      }
      if (this.filterForm.maintenancePerson) {
        params.maintenancePerson = this.filterForm.maintenancePerson
      }
      if (this.filterForm.minCost !== null) {
        params.minCost = this.filterForm.minCost
      }
      if (this.filterForm.maxCost !== null) {
        params.maxCost = this.filterForm.maxCost
      }
      return params
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.loadData()
    },
    
    // 筛选确认
    handleFilterConfirm() {
      this.currentPage = 1
      this.loadData()
      this.showFilterDialog = false
    },
    
    // 筛选关闭
    handleFilterClose() {
      this.showFilterDialog = false
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.loadData()
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadData()
    },
    
    // 新增保养记录
    handleAdd() {
      this.$router.push('/equipment-management/add-maintenance-record')
    },
    
    // 查看详情
    handleView(row) {
      this.currentRecord = { ...row }
      this.showDetailDialog = true
    },
    
    // 编辑保养记录
    handleEdit(row) {
      this.$router.push(`/equipment-management/edit-maintenance-record/${row.maintenanceRecordId}`)
    },
    
    // 删除保养记录
    handleDelete(row) {
      this.$confirm(`确定要删除设备 "${row.equipmentName}" 的保养记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await maintenanceRecordApi.deleteMaintenanceRecord(row.maintenanceRecordId)
          if (response.code === 200) {
            this.$message.success('删除成功')
            this.loadData()
          } else {
            this.$message.error(response.message || '删除失败')
          }
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.maintenance-record {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 20px 30px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.main-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #ebeef5;
}

.action-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.action-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.search-btn {
  margin-left: 5px;
}

.filter-btn {
  margin-left: 5px;
}

.table-container {
  padding: 0 30px;
}

.action-link {
  color: #409EFF !important;
  text-decoration: none;
  margin: 0 5px;
  cursor: pointer;
  background: none;
  border: none;
  padding: 0;
}

.action-link:hover {
  color: #66b1ff !important;
  text-decoration: underline;
}

.delete-link {
  color: #F56C6C;
}

.delete-link:hover {
  color: #f78989;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 30px;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .maintenance-record {
    padding: 10px;
  }
  
  .action-bar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .action-right {
    justify-content: space-between;
  }
  
  .search-input {
    width: 200px;
  }
  
  .table-container {
    padding: 0 15px;
    overflow-x: auto;
  }
  
  .pagination-container {
    padding: 15px;
  }
}
</style>